<template>
  <div class="package-view">
    <div class="header">
      <h2>应用下载</h2>
    </div>
    <el-card shadow="hover" v-infinite-scroll="loadMore" infinite-scroll-distance="50">
      <el-collapse>
        <el-collapse-item
          v-for="pkg in packageList"
          :key="pkg.id"
          :title="pkg.fileName"
        >
          <template #title>
            <div class="collapse-title">
              <span>{{ pkg.fileName }}</span>
              <div class="button-group">
                <el-button type="primary" size="small" @click.stop="handleLocalDownload(pkg.filePath, pkg.fileName)">本地下载</el-button>
                <el-button type="success" size="small" @click.stop="handleOfficialDownload(pkg.officialUrl)">官网下载</el-button>
              </div>
            </div>
          </template>
          <div class="package-content">
            <img :src="pkg.iconUrl || defaultImage" class="package-icon" @error="handleImageError" />
            <div class="package-info">
              <p><strong>文件名:</strong> {{ pkg.fileName }}</p>
              <p><strong>路径:</strong> {{ pkg.filePath }}</p>
              <p><strong>文件大小:</strong> {{ formatFileSize(pkg.fileSize) }}</p>
              <p><strong>版本号:</strong> {{ pkg.version }}</p>
              <p><strong>后缀名:</strong> {{ pkg.suffix }}</p>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
      <div v-if="loading" class="loading">加载中...</div>
      <div v-if="!hasMore" class="no-more">没有更多数据了</div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { usePackageStore } from '@/stores/api/package';
import { downloadFile } from '@/stores/util/file';

const router = useRouter();
const route = useRoute();
const packageStore = usePackageStore();

const searchQuery = ref('');
const packageList = ref([]);
const defaultImage = 'https://picsum.photos/64/64?random=0';
const currentPage = ref(0);
const pageSize = 20;
const total = ref(0);
const loading = ref(false);
const hasMore = ref(true);

const handleImageError = (e: Event) => {
  (e.target as HTMLImageElement).src = defaultImage;
};

const formatFileSize = (size: number) => {
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
  if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(2)} MB`;
  return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
};

const handleLocalDownload = async (filePath: string, fileName: string) => {
  try {
    await downloadFile(filePath, fileName);
    ElMessage.success('开始下载: ' + fileName);
  } catch (error: any) {
    ElMessage.error('下载失败: ' + error.message);
  }
};

const handleOfficialDownload = (url: string) => {
  if (url) {
    window.open(url, '_blank');
  } else {
    ElMessage.warning('官网链接不可用');
  }
};

const fetchPackages = async (page: number) => {
  try {
    loading.value = true;
    const packages = await packageStore.fetchPackages(page, pageSize);
    if (page === 0) {
      packageList.value = packages;
    } else {
      packageList.value = [...packageList.value, ...packages];
    }
    total.value = packageStore.total;
    hasMore.value = packages.length === pageSize;
  } catch (error: any) {
    ElMessage.error('加载安装包失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

const searchPackages = async (query: string) => {
  try {
    loading.value = true;
    const packages = await packageStore.searchPackages(query);
    packageList.value = packages;
    total.value = packageStore.total;
    hasMore.value = packages.length === pageSize;
  } catch (error: any) {
    ElMessage.error('搜索安装包失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

const loadMore = () => {
  if (loading.value || !hasMore.value) return;
  currentPage.value += 1;
  fetchPackages(currentPage.value);
};

watch(
  () => route.query.q,
  (newQuery) => {
    searchQuery.value = (newQuery as string) || '';
    if (searchQuery.value) {
      searchPackages(searchQuery.value);
    } else {
      fetchPackages();
    }
  },
);

onMounted(() => {
  searchQuery.value = (route.query.q as string) || '';
  if (searchQuery.value) {
    searchPackages(searchQuery.value);
  } else {
    fetchPackages(0);
  }
});
</script>

<style scoped>
.package-view {
  width: 80%;
  margin: 40px auto 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  font-size: 24px;
  color: #333;
  flex-grow: 1;
  text-align: center;
}

.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-collapse {
  border: none;
  background-color: transparent;
}

.el-collapse-item__header {
  font-size: 16px;
  color: #333;
  padding: 10px 20px;
  background-color: transparent;
  border-bottom: 1px solid #ebeef5;
}

.collapse-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.button-group {
  display: flex;
  gap: 10px;
  padding-right: 20px;
}

.package-content {
  display: flex;
  padding: 10px 20px;
}

.package-icon {
  width: 64px;
  height: 64px;
  margin-right: 20px;
  object-fit: cover;
}

.package-info p {
  margin: 5px 0;
  font-size: 14px;
  color: #666;
}

.el-collapse-item__content {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.loading,
.no-more {
  text-align: center;
  padding: 20px;
  color: #999;
}
</style>